import React, {useLayoutEffect, useMemo, useState} from 'react';
import {View, ScrollView, processColor} from 'react-native';
import {useTranslation} from 'react-i18next';
import {deviceApi} from '@/services/api/deviceApi';
import {Text, useAppTheme, Card} from 'tsun-smart-ui';
import {unitMap} from '@/enums/statistics';
import Segmented from '@/components/Segmented';
import {DatePickerStep} from '@/pages/scene/Owner/statistics';
import Barchart from '@/components/BarChart';
import useDatePicker from '@/hooks/useDatePicker';
import {withCancelable} from '@/utils';
import CustomLegend from '@/components/CustomLegend';
import {ColorItem} from '@/store/slices/landscapeColorsSlice';
import {selectCurrentDevice} from '@/store/slices/deviceSlice';
import {useSelector} from 'react-redux';
import Logo from '@/components/Logo';
const queryGenEle = withCancelable(deviceApi.queryGenEle);
type DatePickerMode = 'year' | 'month' | 'day';
const StatisticsPage = () => {  
  const {t} = useTranslation();
  const theme = useAppTheme();
  const [colors, setColors] = useState<ColorItem[]>([]);
  useLayoutEffect(() => {
    setColors([
      {
        color: theme.colors?.info?.primary!,
        title: t('device.electricity_production'),
        visible: true,
      },
    ]);
  }, [t]);
  // 年份选择器状态
  const [selected, setSelected] =
    useState<DatePickerMode>('month');
  // 数据状态
  const options = Object.entries(unitMap).map(([key, value]) => ({
    label: t(value),
    value: key as DatePickerMode,
  }));
  const currentDevice = useSelector(selectCurrentDevice);
  const params = useMemo(() => {
    return {
      deviceSns: [currentDevice?.sn],
      deviceType: currentDevice?.deviceType,
      stationId: currentDevice?.stationId,
    };
  }, [currentDevice]);
  const {
    Picker: picker,
    selectedValue: value,
    setSelectedValue: setValue,
    result: totalData,
    chartRef,
    currentUnit,
  } = useDatePicker(selected, queryGenEle, params);
  const totalDataComputed = useMemo(() => {
    const total = (totalData.powerGen ?? []).reduce(
      (sum, item) => sum + item.powerGen,
      0,
    );
    const average = total / (totalData.powerGen?.length ?? 0);
    return {
      total: total === 0 ? '--' : total.toFixed(2),
      average: !!average ? average.toFixed(2) : '--',
      // peak: totalData.reduce(
      //   (max, item) => (max.powerGen > item.powerGen ? max : item),
      //   totalData[0],
      // ),
    };
  }, [totalData]);

  return (
    <ScrollView className=" mx-4">
      <Card className="mt-3">
        <Segmented
          buttons={options}
          value={currentUnit}
          //@ts-ignore
          onChange={setSelected}
        />
        <DatePickerStep
          disabled={currentUnit === 'total'}
          type={currentUnit}
          value={value}
          setValue={setValue}
          onPress={() => {
            picker.show();
          }}></DatePickerStep>
        <View
          style={{
            aspectRatio: 1.64 / 1,
          }}>
          <Barchart
            scaleYEnabled={false}
            ref={chartRef}
            leftUnit={`${t('workplace.unit')}:kWh`}
            showLegend={false}
            dataSetsConfig={colors.map(item => {
              const currentColor = processColor(item.color);
              return {
                color: currentColor,
                drawValues: false,
                visible: item.visible ?? true,
                fillAlpha: 100,
              };
            })}
            yAxis={{
              right: {
                enabled: false,
              },
            }}
            marker={`${t('sys.app.time')}: `}
            xAxisLabels={totalData.powerGen?.map(item => item.time)}
            title={colors.map(item => item.title)}
            chartData={[
              totalData.powerGen?.map(item => item.powerGen ?? 0) ?? [],
            ]}
            highlightPerTapEnabled={colors.some(item => item.visible)}
          />
        </View>
        <View className="mt-3 mb-5">
          <CustomLegend colors={colors} setColors={setColors} />
        </View>
        <View className="flex-row flex-between">
          <View className="flex-row items-center gap-2">
            <Logo
              name="device-statistics"
              round={false}
              backgroundColor={theme.colors?.brand?.primaryLight!}
              color={theme.colors?.brand?.primary!}
            />
            <Text variant="cardTitle">
              {t(unitMap[currentUnit]) +
                t('device.generationStatistics', {
                  defaultValue: '发电量总计',
                })}
            </Text>
          </View>
          <Text
            className=" font-heading"
            style={{
              color: theme.colors?.brand?.primary,
            }}
            variant="titleLarge">
            {totalDataComputed?.total ?? 0}kWh
          </Text>
        </View>
        <View className="flex-row items-center gap-x-2 mt-5">
          <View className="flex-1">
            <Text
              variant="caption"
              style={{
                color: theme.colors?.neutral?.primary,
              }}>
              {t(unitMap[currentUnit]) +
                t('device.averagePowerGeneration', {
                  defaultValue: '平均发电量',
                })}
            </Text>
            <Text variant="navTitle" className="font-body">
              {totalDataComputed?.average ?? 0}kWh
            </Text>
          </View>
        </View>
      </Card>
    </ScrollView>
  );
};

export default StatisticsPage;
